#coding=utf-8
"""
用户api模块
"""
from tornado.gen import coroutine
from sqlalchemy import or_, desc
from ..tools import unblock, to_json
from ..models import User
from .base import BaseApiHandler


class UserHandler(BaseApiHandler):
    """
    用户API
    """
    __url_names__ = []


    @coroutine
    def check_user_id_not_exist(self, user_id):
        """
        检查用户ID存在
        """
        user = self.db_conn.query(User).filter_by(user_id=user_id, is_deleted=False).first()
        if user:
            self.error('指定用户ID已被使用')
            return False
        return True

    @coroutine
    def check_id_exist(self, id):
        """
        检查用户存在
        """
        user = self.db_conn.query(User).filter_by(id=id, is_deleted=False).first()
        if not user:
            self.error('指定用户不存在')
        return user


class ListHandler(UserHandler):
    """
    记录列表
    """
    __urls__ = [r'/api/user/?']

    @unblock
    def get(self):
        """
        获取记录列表
        :return:
        """
        # 分页大小
        size = int(self.get_query_argument('size', 0))
        # 第几项开始
        start = int(self.get_query_argument('start', 0))
        # 查询字段
        query = self.get_query_argument('query', '')
        # 排序字段
        order = self.get_query_argument('order', '')
        # 正序或倒叙
        sort = self.get_query_argument('dir', '')
        end = start + size
        items = self.db_conn.query(User).filter_by(is_deleted=False)
        if query:
            items = items.filter(
                or_(
                    User.user_id.like('%' + query + '%'),
                    User.name.like('%' + query + '%')
                )
            )
        if order:
            if sort == 'desc':
                items = items.order_by(desc(getattr(User, order)))
            else:
                items = items.order_by(getattr(User, order))
        # 总件数
        total = items.count()
        if end:
            # 分页处理
            items = items.slice(start, end)
        # 获取list对象
        items = items.all()
        # 返回值
        self.success(items, total=total)
